package nio.two;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/*
    NIO下的通信入门案例---服务端
 */
public class Server {
    public static void main(String[] args) {
        try {
            //创建服务端管道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            //设置端口
            serverSocketChannel.bind(new InetSocketAddress(9999));
            //创建选择器
            Selector selector = Selector.open();
            //将通道注册到选择器上,并且指定为监听事件状态
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            //使用这个选择器轮询已经就绪好的事件
            while (selector.select() > 0) {
                //获取注册在该选择器上的通道上已经就绪好的事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                //遍历所有就绪的事件
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    //判断事件的类型，如果是监听类型
                    if (next.isAcceptable()) {
                        //获取当前接入的客户端的通道
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (next.isReadable()) {    //如果是读事件
                        //获取当前读事件
                        SocketChannel socketChannel = (SocketChannel) next.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        while ((len = socketChannel.read(buffer)) != 0) {
                            //切换为读模式
                            buffer.flip();
                            System.out.println(new String(buffer.array(),0,len));
                            //清空缓冲区
                            buffer.clear();
                        }
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
